package top.codef.secure.config.delegates;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

import top.codef.secure.config.interfaces.CerberusHttpSecurityConfig;
import top.codef.secure.config.interfaces.LogoutSuccessDecorator;
import top.codef.secure.handlers.CerberusLogoutSuccessHandler;
import top.codef.secure.properties.CerberusLogoutProperties;

@Configuration
@EnableConfigurationProperties(CerberusLogoutProperties.class)
@Order(7)
public class CerberusLogoutConfig implements CerberusHttpSecurityConfig {

	@Autowired
	private CerberusLogoutProperties cerberusLogoutProperties;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private LogoutSuccessDecorator logoutSuccessDecorator;

	private final Log logger = LogFactory.getLog(CerberusLogoutConfig.class);

	@Override
	public void secure(HttpSecurity httpSecurity) throws Exception {
		logger.debug("登出设置");
		httpSecurity.logout(x -> {
			var logoutConfigurer = x.addLogoutHandler(new SecurityContextLogoutHandler())
					.logoutUrl(cerberusLogoutProperties.getLogoutPath())
					.logoutSuccessHandler(new CerberusLogoutSuccessHandler(objectMapper, logoutSuccessDecorator,
							cerberusLogoutProperties));
			if (cerberusLogoutProperties.isClearCookie())
				logoutConfigurer.addLogoutHandler(new CookieClearingLogoutHandler("JSESSIONID"));
		});

	}

}
